<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="快递名称" prop="deliveryName">
        <el-input
          v-model="queryParams.deliveryName"
          placeholder="请输入快递名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="快递单号" prop="deliveryId">
        <el-input
          v-model="queryParams.deliveryId"
          placeholder="请输入快递单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="uid">
        <el-input
          v-model="queryParams.uid"
          placeholder="请输入用户ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品ID" prop="pid">
        <el-input
          v-model="queryParams.pid"
          placeholder="请输入商品ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="status">
        <el-select
          v-model="queryParams.category"
          placeholder="请选择分类"
          clearable
          size="small"
        >
          <el-option
            label="请选择字典生成"
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="payType">
        <el-select
          v-model="queryParams.payType"
          placeholder="请选择支付方式"
          clearable
          size="small"
        >
          <el-option
            label="请选择字典生成"
            v-for="item in payTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="createTime">
        <el-date-picker
          v-model="payTime"
          type="daterange"
          :picker-options="pickerOptions"
          placeholder="请选择支付时间"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item style="display: block">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ds:productOrder:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ds:productOrder:edit']"
          >修改</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ds:productOrder:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ds:productOrder:export']"
          >导出</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addOrderDialog = true"
          >加单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="single"
          icon="el-icon-minus"
          size="mini"
          @click="minusOrderDialogClick"
          >退单</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="productOrderList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="120" />
      <el-table-column label="用户ID" align="center" prop="uid" width="120" />
      <el-table-column
        label="姓名"
        align="center"
        prop="realName"
        width="120"
      />
      <el-table-column label="用户电话" align="center" prop="userPhone" />
      <el-table-column
        label="商品"
        align="center"
        prop="productName"
        width="220"
      />
      <el-table-column
        label="购买数量"
        align="center"
        prop="totalNum"
        width="100"
      />
      <el-table-column
        label="总价"
        align="center"
        prop="totalPrice"
        width="100"
      />
      <el-table-column
        label="订单号"
        align="center"
        prop="orderId"
        width="150"
      />
      <el-table-column
        label="订单状态"
        align="center"
        prop="shipmentStatus"
        width="80"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.shipmentStatus == 0">未发货</span>
          <span v-if="scope.row.shipmentStatus == 1">待收货</span>
          <span v-if="scope.row.shipmentStatus == 2">已收货</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="userAddress" />
      <el-table-column label="支付时间" align="center" prop="createTime" />

      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="uid">
          <el-input
            disabled="disabled"
            v-model="form.uid"
            placeholder="请输入用户id"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input
            disabled="disabled"
            v-model="form.realName"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="用户电话" prop="userPhone">
          <el-input
            disabled="disabled"
            v-model="form.userPhone"
            placeholder="请输入用户电话"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="userAddress">
          <el-input
            disabled="disabled"
            v-model="form.userAddress"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="商品ID" prop="pid">
          <el-input
            disabled="disabled"
            v-model="form.pid"
            placeholder="请输入商品ID"
          />
        </el-form-item>
        <el-form-item label="商品" prop="productName">
          <el-input
            disabled="disabled"
            v-model="form.productName"
            placeholder="请输入商品"
          />
        </el-form-item>
        <el-form-item label="购买数量" prop="totalNum">
          <el-input
            disabled="disabled"
            v-model="form.totalNum"
            placeholder="请输入购买数量"
          />
        </el-form-item>
        <el-form-item label="订单编号" prop="totalPrice">
          <el-input
            disabled="disabled"
            v-model="form.totalPrice"
            placeholder="请输入订单总价"
          />
        </el-form-item>
        <el-form-item label="订单号" prop="totalPrice">
          <el-input
            disabled="disabled"
            v-model="form.orderId"
            placeholder="订单号"
          />
        </el-form-item>
        <el-form-item label="快递单号" prop="totalPrice">
          <el-input v-model="form.delivery_id" placeholder="订单号" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
              >{{ dict.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 加单单对话框 -->
    <el-dialog
      title="加单"
      :visible.sync="addOrderDialog"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="addform"
        :model="addQuery"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商品ID" prop="productId">
          <el-input
            v-model="addQuery.productId"
            placeholder="请输入商品ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="addQuery.userId"
            placeholder="请输入用户ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="数量" prop="totalNum">
          <el-input
            v-model="addQuery.totalNum"
            placeholder="请输入商品数量"
            clearable
          />
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="primary" @click="addOrderClick">确 定</el-button>
          <el-button @click="addOrderDialog = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 减单对话框 -->
    <el-dialog
      title="减单"
      :visible.sync="minusOrderDialog"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="minusform"
        :model="chargebackQuery"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="订单ID" prop="id">
          <el-input
            v-model="chargebackQuery.id"
            placeholder="请输入订单ID"
            clearable
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="退款金额" prop="refundPrice">
          <el-input
            v-model="chargebackQuery.refundPrice"
            placeholder="请输入退款金额"
            clearable
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="退款原因" prop="refundReasonWap">
          <el-input
            v-model="chargebackQuery.refundReasonWap"
            type="textarea"
            placeholder="请输入退款原因"
            clearable
          />
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="primary" @click="minusOrderClick">确 定</el-button>
          <el-button @click="minusOrderDialog = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProductOrder,
  getProductOrder,
  delProductOrder,
  addProductOrder,
  updateProductOrder,
  exportProductOrder,
} from "@/api/ds/productOrder";
import { addAchievement, chargeback } from "@/api/ds/orderManage";

export default {
  name: "ProductOrder",
  components: {},
  data() {
    var validateID = (rule, value, callback) => {
      if (value) {
        if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
          callback(new Error("请输入正确的值"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入值"));
      }
    };
    return {
      // 遮罩层
      loading: true,
      pickerOptions: {
        // 设置不能选择的日期
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate0 = minDate.getTime();
          if (maxDate) {
            this.choiceDate0 = "";
          }
        },
        disabledDate: (time) => {
          let choiceDateTime = new Date(this.choiceDate0).getTime();
          const minTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() - 1
          );
          const maxTime = new Date(choiceDateTime).setMonth(
            new Date(choiceDateTime).getMonth() + 1
          );
          const min = minTime;
          const newDate =
            new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1;
          const max = newDate < maxTime ? newDate : maxTime;
          //如果已经选中一个日期 则 返回 该日期前后一个月时间可选
          if (this.choiceDate0) {
            return time.getTime() < min || time.getTime() > max;
          }
          //若一个日期也没选中 则 返回 当前日期以前日期可选
          return time.getTime() > newDate;
        },
      },
      // 选中数组
      ids: [],
      totalPrice: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      productOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 加单弹出层
      addOrderDialog: false,
      // 减单弹出层
      minusOrderDialog: false,
      payTime: null, //时间选择器
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        orderId: null,
        uid: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        pid: null,
        productName: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        payTime: null,
        payType: null,
        status: null,
        refundStatus: null,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        isDel: null,
        cost: null,
        shippingType: null,
        channel: null,
        isSystemDel: null,
        regionalPerformance: null,
        communityPerformance: null,
        netBodyNumber: null,
      },
      // 订单状态字典
      statusOptions: [
        // 3未发货 4已发货 5已收货
        { dictValue: "3", dictLabel: "未发货" },
        { dictValue: "4", dictLabel: "已发货" },
        { dictValue: "5", dictLabel: "已收货" },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        uid: [{ required: true, message: "用户id不能为空", trigger: "blur" }],
        userId: [{ required: true, validator: validateID, trigger: "blur" }],
        productId: [{ required: true, validator: validateID, trigger: "blur" }],
        totalNum: [{ required: true, validator: validateID, trigger: "blur" }],
        refundReasonWap: [
          { required: true, message: "退款原因不能为空", trigger: "blur" },
        ],
      },
      categoryOptions: [
        {
          // 分类下拉框
          value: "0-100",
          label: "现金",
        },
        {
          value: "101-200",
          label: "积分",
        },
        {
          value: "201-300",
          label: "事业",
        },
      ],
      payTypeOptions: [
        {
          // 支付方式下拉框
          value: "1",
          label: "支付宝",
        },
        {
          value: "2",
          label: "微信",
        },
        {
          value: "3",
          label: "余额",
        },
        {
          value: "4",
          label: "银行卡",
        },
        {
          value: "5",
          label: "系统",
        },
      ],
      addQuery: {
        // 加单 请求参数
        productId: "", //商品id
        userId: "", //用户id
        totalNum: "", //数量
      },
      chargebackQuery: {
        id: "", // 订单id
        refundReasonWap: "", // 退款原因
        refundPrice: "", //退款金额
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 订单状态字典翻译
    // statusFormat(row, column) {
    //   return this.selectDictLabel(this.statusOptions, row.status);
    // },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      let q = this.addDateRange(this.queryParams, this.payTime, "");

      listProductOrder(q).then((response) => {
        this.productOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        uid: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        pid: null,
        productName: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        payTime: null,
        payType: null,
        status: 0,
        refundStatus: 0,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        isDel: null,
        cost: null,
        shippingType: null,
        channel: null,
        isSystemDel: null,
        remark: null,
        createTime: null,
        regionalPerformance: null,
        communityPerformance: null,
        netBodyNumber: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.totalPrice = selection.map((item) => item.totalPrice);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      // 判断如果是未支付订单，不可退单
      if (selection.length === 1 && selection[0].status == 6) {
        this.single = true;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProductOrder(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 加单按钮操作 */
    addOrderClick() {
      this.$refs["addform"].validate((valid) => {
        if (valid) {
          console.log("this.addQuery = " + JSON.stringify(this.addQuery));
          addAchievement(this.addQuery).then((res) => {
            if (res.code === 200) {
              this.$message.success("加单成功");
              this.reset();
              this.getList();
              this.addOrderDialog = false;
            } else {
              this.$message.error("加单失败");
            }
          });
        }
      });
    },
    /** 减单按钮操作 */
    minusOrderDialogClick(row) {
      const id = row.id || this.ids[0];
      const totalPrice = this.totalPrice[0] || 0;
      this.chargebackQuery.id = id;
      this.chargebackQuery.refundPrice = totalPrice;
      this.minusOrderDialog = true;
    },
    /** 减单确定按钮操作 */
    minusOrderClick() {
      this.$refs["minusform"].validate((valid) => {
        if (valid) {
          chargeback(this.chargebackQuery).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.reset();
              this.getList();
              this.minusOrderDialog = false;
            } else {
              this.$message.error("减单失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateProductOrder(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductOrder(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除订单编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delProductOrder(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有订单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportProductOrder(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
